package cn.edu.bupt.ch5_1.controller;

import cn.edu.bupt.ch5_1.common.Result;
import cn.edu.bupt.ch5_1.entity.Account;
import cn.edu.bupt.ch5_1.mapper.AccountMapper;

import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.List;

@Tag(name = "账户接口")
@RestController
@RequestMapping("/api/v1/account")
public class AccountController {
    @Resource
    private AccountMapper accountMapper;

    @Operation(summary = "获取账户列表", description = "返回值为全部的账户列表")
    @GetMapping(path = "/", produces = "application/json")
    public Result<?> listAll() {
        List<Account> accounts = accountMapper.selectList(null);
        return Result.ok(accounts);
    }

    @Operation(summary = "转账", description = "转账")
    @GetMapping(path = "/trans", produces = "application/json")
    @Transactional(isolation = Isolation.SERIALIZABLE)
    public Result<?> trans() throws InterruptedException {
        BigDecimal amount = new BigDecimal(100);
        Account accountSrc = accountMapper.selectById(1);
        System.out.println("AAA balance:"+accountSrc.getBalance());
        accountSrc.setBalance(accountSrc.getBalance().subtract(amount));
        System.out.println("AAA before update:"+accountSrc.getBalance());
        accountMapper.updateById(accountSrc);
        System.out.println("AAA after update:"+accountSrc.getBalance());
        System.out.println("BBB start select");
        Account accountDst = accountMapper.selectById(2);
        System.out.println("BBB balance:"+accountDst.getBalance());
        accountDst.setBalance(accountDst.getBalance().add(amount));
        accountMapper.updateById(accountDst);
        System.out.println("BBB after update:"+accountDst.getBalance());
        return Result.ok();
    }

}
